package edu.umn.contactviewer;

import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.provider.ContactsContract.Profile;
import android.util.Log;

public class UpdateContactTask extends AsyncTask<Contact, Void, Contact> {
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		// create a progress dialog
	}

	String URL_BASE = "http://contacts.tinyapollo.com/";
	String API_KEY = "idroid";

	@Override
	protected Contact doInBackground(Contact... params) {
		try {
			AndroidHttpClient client = AndroidHttpClient.newInstance("Android",
					null);

			Contact c = params[0];
			
			String updateString = c.get_id().trim()
					+ "?key=" + API_KEY + "&name=" + c.getName().trim() + "&phone="
					+ c.getPhone().trim() + "&twitterId=" + c.getTwitterId().trim()
					+ "&email=" + c.getEmail().trim() + "&title=" + c.getTitle().trim();
			

			HttpPut put = new HttpPut(URL_BASE + "contacts/" + updateString.replace(" ", "%20"));

			HttpResponse response = client.execute(put);

			Gson gson = new Gson();

			Contact result = gson.fromJson(new InputStreamReader(response
					.getEntity().getContent()), Contact.class);
			client.close();

			return result;
		} catch (Exception ex) {
			Log.w("GetContactTask", "Error getting contact", ex);
		}
		return null;
	}

	@Override
	protected void onPostExecute(Contact result) {
		super.onPostExecute(result);
		// close the progress dialog and tell the activity that you've received
		// a result
	}

}